﻿/*----------------------------------------------------------------
//  <copyright file="BasicAuthAuthorizationFilter.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2024-03-04 14:49</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Hangfire.Dashboard.Authorization
{
    #region "表示基本身份验证的Hangfire授权筛选器"
    /// <summary>
    /// 表示基本身份验证的Hangfire授权筛选器
    /// （Represents Hangfire authorization filter for basic authentication）
    /// </summary>
    public class BasicAuthAuthorizationFilter : IDashboardAuthorizationFilter
    {
        /// <summary>
        /// 表示Hangfire基本身份验证的选项
        /// </summary>
        private readonly BasicAuthAuthorizationFilterOptions _options;

        #region "构造函数"
        #region "初始化一个基本身份验证的Hangfire授权筛选器的新实例"
        /// <summary>
        /// 初始化一个基本身份验证的Hangfire授权筛选器 <see cref="BasicAuthAuthorizationFilter"/> 的新实例
        /// </summary>
        public BasicAuthAuthorizationFilter()
            : this(new BasicAuthAuthorizationFilterOptions())
        { }
        #endregion
        #region "初始化一个基本身份验证的Hangfire授权筛选器的新实例"
        /// <summary>
        /// 初始化一个基本身份验证的Hangfire授权筛选器 <see cref="BasicAuthAuthorizationFilter"/> 的新实例
        /// </summary>
        /// <param name="options">Hangfire基本身份验证的选项</param>
        public BasicAuthAuthorizationFilter(BasicAuthAuthorizationFilterOptions options)
        {
            _options = options;
        }
        #endregion

        #endregion

        #region "方法"
        #region "授权"
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize(DashboardContext context)
        {
            HttpContext httpContext = context.GetHttpContext();

            if (_options.SslRedirect && !httpContext.Request.IsHttps)
            {
                httpContext.Response.OnStarting(async state =>
               {
                   string redirectUri = new UriBuilder("https", httpContext.Request.Host.Host, httpContext.Request.Host.Port.CastTo(80), httpContext.Request.Path.Value).ToString();

                   httpContext.Response.StatusCode = 301;
                   httpContext.Response.Redirect(redirectUri);

                   await Task.CompletedTask;
               }, null);
                return false;
            }

            if (_options.RequireSsl && !httpContext.Request.IsHttps)
            {
                httpContext.Response.WriteAsync("需要安全连接才能访问Hangfire仪表板");
                return false;
            }

            string authorization = httpContext.Request.Headers.Authorization;
            if (!string.IsNullOrWhiteSpace(authorization))
            {
                AuthenticationHeaderValue authValues = AuthenticationHeaderValue.Parse(authorization);

                if ("Basic".Equals(authValues.Scheme, StringComparison.InvariantCultureIgnoreCase))
                {
                    string parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter));
                    var parts = parameter.Split(':');

                    if (parts.Length > 1)
                    {
                        string userId = parts[0];
                        string password = parts[1];

                        if (!string.IsNullOrWhiteSpace(userId) && !string.IsNullOrWhiteSpace(password))
                        {
                            return _options
                                .Users
                                .Any(user => user.Validate(userId, password, _options.LoginCaseSensitive))
                                   || Challenge(httpContext);
                        }
                    }
                }
            }

            return Challenge(httpContext);
        }
        #endregion

        #endregion

        #region "私有方法"
        #region "跳转授权登录页面"
        /// <summary>
        /// 跳转授权登录页面
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static bool Challenge(HttpContext httpContext)
        {
            httpContext.Response.StatusCode = 401;
            httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");

            httpContext.Response.WriteAsync("需要身份验证");

            return false;
        }
        #endregion

        #endregion

    }
    #endregion

}
